package com.javiercp.ayudaapp.preferences;

import java.io.Reader;
import java.io.StringReader;
import java.util.Iterator;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import com.javiercp.ayudaapp.MyConstants;

import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.util.Log;

public class ContactsPreferenceInflaterSDK5 extends ContactsPreferenceInflater {

	@Override
	public void inflate(String xml, PreferenceCategory pref) {
		if (xml == "") return;
		
		Reader reader = new StringReader(xml);
		Serializer serializer = new Persister();
		
		try
		{
			ContactDataList list = serializer.read(ContactDataList.class, reader, false);
			
			for (Iterator<ContactData> iterator = list.getContacts().iterator();iterator.hasNext();) {
				addPreference(iterator.next(), pref);
			}
		}
		catch (Exception ex)
		{
			Log.e(MyConstants.LOGTAG, "Error deserializing object.", ex);
		}
	}
	
	@Override
	public ContactDataList deserialice(String xml) {
		if (xml == "") return null;
		
		Reader reader = new StringReader(xml);
		Serializer serializer = new Persister();
		
		ContactDataList list = null;
		
		try
		{
			list = serializer.read(ContactDataList.class, reader, false);
		}
		catch (Exception ex)
		{
			Log.e(MyConstants.LOGTAG, "Error deserializing object.", ex);
		}
		
		return list;
	}
	
	private void addPreference(ContactData contactData, PreferenceCategory pref)
	{
		Preference newPref = new Preference(pref.getContext());
		newPref.setTitle(contactData.getName());
		newPref.setSummary(contactData.getSummaryName());
		newPref.setKey("DYNAMIC_PREF" + pref.getPreferenceCount());
		
        pref.addPreference(newPref);
	}
	
}
